Ploty Package - An Introduction

Introduction

Today, we will cover the “plotly” package and explore it using a variety of data sets. First, we will start by uploading the packages that will be needed today. If these packages do not load, be sure to install them.

Functions

This package can be used in a variety of ways to make data interactive and fun. The functions we will be exploring today are:

  1. add_surface
  2. plot_ly
  3. animation
  4. add_trace
  5. colorbar
  6. layout
  7. add_text
library(plotly)
library(tidyverse)
library(here)
library(readr)
library(maps)
library(dplyr)
library(ggplot2)
library(lubridate)
library(purrr) #Used to  create the animation frames
library(rmdformats)
library(heatmaply)
library(palmerpenguins)
library(reticulate)

3D Chart Example

Load Data

CherryTree_Data_ <- read_csv(here("Data/CherryTree Data .csv")) # Load data

Change to a numeric matrix

CherryTree <- as.matrix(CherryTree_Data_) # change the data set to a numeric matrix 

Plot numeric matrix

fig <- plot_ly(z = ~CherryTree) # plot by numeric matrix 
fig<- fig %>% add_surface()

save_image(fig, here("Output", "3DPlot.png"))

View figure

fig # Display plot

An example of an animation timeseries

data("economics") # Load in dataset that is already built into R

Mutate Data

econ <- economics %>% # Subset data
  mutate(cumulative_pop = cumsum(pop)) # Creates a new column

Create a filled area plot with an animation frame

fig2 <- econ %>%
  plot_ly(x = ~date,  # Specify x and y variables of interest
          y = ~cumulative_pop, 
          fill = ~pop,
          type = "scatter", # Insert graph type
          mode = "none",
          stackgroup = "one",
          animation_frame = ~year(date)) %>% # 
    add_trace(y = ~0, 
              hoverinfo = "skip", 
              showlegend = FALSE) %>%
    layout(title = "US Population Over Time",
           xaxis = list(title = "Date"),
           yaxis = list(title = "Cumulative Population")) %>%
    colorbar(title = "Population", len = 0.5, y = 0.8, ypad = 0)

fig2
save_image(fig2, here("Output", "Econ.png"))

Our goal is to look at the median population data for the state of California from 2000 and 2010. Note: Plotly has built-in Country and State Geometries.

Now let’s explore another graph type with this package. We will create a scatter plot with this data to create interactive points.

Load Data

chemicaldata <- read_csv(here("Data/chemicaldata.csv")) # Load data

Create a scatter mapbox plot with the latitude and longitude data

fig3 <- plot_ly(chemicaldata, type = "scattermapbox", # Specify df, graph type, and etc.
                             mode = "markers", 
                             marker = list(size = 10, 
                                           color = "red"), 
                                           lon = ~Long, lat = ~Lat)

Set the map layout

fig3 <- fig3 %>% layout(mapbox = list(center = list(lon = -157.763, 
                                                  lat = 21.274),
                                                  zoom = 15, 
                                                  style = "open-street-map"))

Show the map

fig3 # Show the map
save_image(fig3, here("Output", "ChemData.png"))

2D Histogram Example Using Penguin Data

plot_ly( 
  data = penguins, 
  alpha = 0.6, 
  x = ~bill_depth_mm, 
  y = ~species, 
  type = "histogram2d", 
  text = ~paste('</br> species:', species, 
                '</br> bill depth', bill_depth_mm)) %>% 
  layout(title = "A Measure of Penguin Bill Depth and Islands", 
         xaxis = list(title = "Bill Depth (mm)"), 
         yaxis = list(title = "Species"))

Heatmap example using penguin data (need to make more edits)

penguinplot <- as.matrix(penguins_raw) # Change data set to matrix

fig4<- plot_ly(z = ~penguinplot, type = "heatmap") 

View Plot

fig4
save_image(fig4, here("Output", "Heatmap.png"))

Bar Chart

Load Data

data("msleep") # Load data

Create bar plot

sleep_bar <-msleep %>%
             plot_ly(x = ~order, 
                     y = ~sleep_rem,
                     type = "bar", 
                     name = "REM Sleep")

Add layout information

sleep_bar <- sleep_bar %>% 
  layout(title = "Average REM Sleep by Order", 
         xaxis = list(title = "Animal Order"), 
         yaxis = list(title = "REM Sleep (hours)"))

Show plot

sleep_bar
save_image(sleep_bar, here("Output", "sleep_bar.png"))

THINK, PAIR, AND SHARE

Can you create a similar graph but show the average REM sleep by each genus?

Load Data

data(msleep) # Load Data

Subset data set

msleep <- ggplot2::msleep %>% # we need to assign the data set "msleep" found in ggplot and assign it to our current RMarkdown.
  rename(`Type of Diet` = vore, `Total Hours of Sleep` = sleep_total) %>% #changes names before making graph so axis doesn't need to be changed later
  na.omit() #removes any incomplete or N/A data from data set

Create a bar graph

diet_sleep <- msleep %>% # We have assigned our graph the letter Q to request it easily later
  plot_ly(x = ~reorder(`Type of Diet`, -`Total Hours of Sleep`), 
          y = ~`Total Hours of Sleep`, # changing the order of how the bars show up so they're increasing in hours of sleep.
          type = 'bar', # type of graph
          marker = list(color = rainbow(nrow(msleep), #uses rainbow colors for bars indicating their sleeping hours individually and as a dietary group.
                        alpha = 0.7))) %>% #determines the transparency/opacity of the bars 0.0 being completely transparent
  
  
  layout(xaxis = list(title = "Type of Diet"), #naming x-axis
         yaxis = list(title = "Total Hours of Sleep"), #naming y-axis
         title = "Total Hours of Sleep vs. Type of Diet") #naming graph

Animating your Graph

# Add animation to the bars
diet_sleep <- diet_sleep %>% 
                animation_opts(frame = 100, easing = 'elastic') #controls timing and style of animation,

Displaying our Results

# Display the graph
diet_sleep
save_image(diet_sleep, here("Output", "diet_sleep.png"))

Additional Resources

ggplotly() - Allows you to change ggplot functions into animations.